/*======================================================================
 
 UNLESS OTHERWISE AGREED TO IN A SIGNED WRITING BY HONEYWELL INTERNATIONAL INC
 (“HONEYWELL”) AND THE USER OF THIS CODE, THIS CODE AND INFORMATION IS PROVIDED
 "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING
 BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS
 FOR A PARTICULAR PURPOSE.
 
 COPYRIGHT (C) 2008 HONEYWELL INTERNATIONAL INC.
 
 THIS SOFTWARE IS PROTECTED BY COPYRIGHT LAWS OF THE UNITED STATES OF
 AMERICA AND OF FOREIGN COUNTRIES. THIS SOFTWARE IS FURNISHED UNDER A
 LICENSE AND/OR A NONDISCLOSURE AGREEMENT AND MAY BE USED IN ACCORDANCE
 WITH THE TERMS OF THOSE AGREEMENTS. UNAUTHORIZED REPRODUCTION,  DUPLICATION
 OR DISTRIBUTION OF THIS SOFTWARE, OR ANY PORTION OF IT  WILL BE PROSECUTED
 TO THE MAXIMUM EXTENT POSSIBLE UNDER THE LAW.
 
 ======================================================================*/
//
//  AppDelegate.m
//  SDKTest
//

#import "AppDelegate.h"

#import "DecoderVC.h"
#import "PMVC.h"
#import "DataEngine.h"

#import "LoginViewController.h"

#import "BedViewController.h"
#import "DutyViewController.h"
#import "TurnViewController.h"
#import "SetViewController.h"
#import "InfoViewController.h"
#import "CustomTabBarController.h"
#import "PersonalDutyViewController.h"

#import "ScanService.h"
#import "BatteryView.h"

#define Battery_H   16 //电池高度


@interface AppDelegate(){
    UILabel *lbl;
    UIAlertView*alert;
    NSTimer *timer;
}
@property (assign,nonatomic)BOOL updating;
-(void)updateLabels;


- (void)redirectNSLogToDocumentFolder;

@end

@implementation AppDelegate

@synthesize window = _window;
//@synthesize viewController = _viewController;
@synthesize tabBarController = _tabBarController;
@synthesize isScan=_isScan;

//@synthesize CustomTabBarController = _CustomTabBarController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//   [self redirectNSLogToDocumentFolder];
   self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
   [self gotoLoginPage];   
   [self.window makeKeyAndVisible];
    [[Captuvo sharedCaptuvoDeviceDebug] addCaptuvoDelegate:self];
    [[Captuvo sharedCaptuvoDevice] startDecoderHardware] ;
    [[Captuvo sharedCaptuvoDevice]enableCaptuvoDebug:NO];


       return YES;
   
}
-(void)decoderDataReceived:(NSString *)data{
    AppDelegate  *appDelegate = App;
    appDelegate.isScan=NO;
    appDelegate.Scandata=data;
    
   // int selectedIndex =[appDelegate.tabBarController selectedIndex];
    UINavigationController *selecteNav = (UINavigationController *)appDelegate.tabBarController.selectedViewController;
    if ([selecteNav.visibleViewController isKindOfClass:[NSClassFromString(@"BedViewController") class]]) {//床位
        [[ScanService sharedInstance]postDataReceivedNotify:data andviewname:@"bed"];
        
    }
    if ([selecteNav.visibleViewController isKindOfClass:[NSClassFromString(@"DutyViewController") class]]){
        
        [[ScanService sharedInstance]postDataReceivedNotify:data andviewname:@"duty"];
    }
    
    if ([selecteNav.visibleViewController isKindOfClass:[NSClassFromString(@"AdviceController") class]]){
        [[ScanService sharedInstance]postDataReceivedNotify:data andviewname:@"Advice"];
    }
    if ([selecteNav.visibleViewController isKindOfClass:[NSClassFromString(@"PatientInfoViewController") class]]){
        [[ScanService sharedInstance]postDataReceivedNotify:data andviewname:@"PatientInfoView"];
       // [[DataEngine sharedInstance]showMessage:@"没有找到此条码对应的病人" withTitle:@"PatientInfoView"];
        
    }
    if ([selecteNav.visibleViewController isKindOfClass:[NSClassFromString(@"PersonalDutyViewController") class]]){
        [[ScanService sharedInstance]postDataReceivedNotify:data andviewname:@"PersonalDutyView"];
        
    }
    if ([selecteNav.visibleViewController isKindOfClass:[NSClassFromString(@"TurnViewController") class]]){
        [[ScanService sharedInstance]postDataReceivedNotify:data andviewname:@"TurnView"];
        
    }
    
    //    if(selectedIndex==0)
    //    {
    //        [[ScanService sharedInstance]postDataReceivedNotify:data andviewname:@"bed"];
    //    }
    //
    //    if(selectedIndex==1)
    //    {
    //        [[ScanService sharedInstance]postDataReceivedNotify:data andviewname:@"duty"];
    //    }
    
}


- (void)applicationWillResignActive:(UIApplication *)application
{
   // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
   // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    
    
    [self gotoLoginPage];
   // [timer setFireDate:[NSDate distantFuture]];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
   // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
   // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
   // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
   // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
   // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


-(void)pushTabbar{
    
    
    BedViewController *bedVC = [[BedViewController alloc] init];
    UINavigationController *bedNav = [[UINavigationController alloc] initWithRootViewController:bedVC];
    //bedVC.tabBarItem.image = [UIImage imageNamed:@"put.png"];
    
    bedVC.title= @"床位";
    //PersonalDutyViewController

    DutyViewController *dutyVC = [[DutyViewController alloc] init];
  UINavigationController *dutyNav = [[UINavigationController alloc] initWithRootViewController:dutyVC];
//// //dutyVC.tabBarItem.image = [UIImage imageNamed:@"get.png"];
//    //dutyVC.setupData;
//    //[dutyvc.rightBar_clicked];
     dutyVC.title= @"任务";
    
//  PersonalDutyViewController *dutyVC = [[PersonalDutyViewController alloc] init];
// UINavigationController *dutyNav = [[UINavigationController alloc] initWithRootViewController:dutyVC];
////dutyVC.tabBarItem.image = [UIImage imageNamed:@"get.png"];
//    dutyVC.title= @"任务";
  
    TurnViewController *turnVc = [[TurnViewController alloc] init];
    UINavigationController  *turnNav = [[UINavigationController alloc] initWithRootViewController:turnVc];
    //turnVc.tabBarItem.image = [UIImage imageNamed:@"post.png"];
    turnVc.title= @"流转";
    
    InfoViewController *infoVC = [[InfoViewController alloc] init];
    UINavigationController *infoNav = [[UINavigationController alloc] initWithRootViewController:infoVC];
    //infoVC.tabBarItem.image = [UIImage imageNamed:@"NoImage.png"];
    infoVC.title = @"消息";
    
    SetViewController *setVc = [[SetViewController alloc] init];
    UINavigationController *setNav = [[UINavigationController alloc] initWithRootViewController:setVc];
    //setVc.tabBarItem.image = [UIImage imageNamed:@"B-grid-icon-female.png"];
    setVc.title= @"设置";
    
    
    
    CustomTabBarController *tabBarController = [[CustomTabBarController alloc] init];
    tabBarController.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-Battery_H);
    tabBarController.viewControllers = @[bedNav,dutyNav,turnNav, infoNav,setNav];
    //tabBarController.viewControllers = @[bedNav, turnNav, infoNav,setNav];
    self.tabBarController = tabBarController;
    [self window].rootViewController = self.tabBarController;
    _navRoot = nil;
    
    
    
    [self buildBatteryView];
    // [[App window] makeKeyAndVisible];
    
}

//去登陆界面
-(void)gotoLoginPage{
    
    self.viewController  = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
    _navRoot = [[UINavigationController alloc] initWithRootViewController:self.viewController];
    
    // Override point for customization after application launch.
    self.window.rootViewController =_navRoot;
    self.window.backgroundColor =[UIColor whiteColor];
    //[UIColor colorWithRed:76/255.0 green:214/255.0 blue:193/255.0 alpha:1];

    
    self.tabBarController    = nil;
}

//外壳电量
-(void)buildBatteryView{
    
    [[Captuvo sharedCaptuvoDevice] startDecoderHardware] ;
    //BatteryStatus BatteryStatus = [[Captuvo sharedCaptuvoDevice]getBatteryStatus];
    
    
    
    
    if (!self.batteryView) {
        
        // self.updating = NO;
        /*
         _batteryView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - Battery_H, SCREEN_WIDTH,  Battery_H)];
         [self.window addSubview:_batteryView];
         _batteryView.backgroundColor = [UIColor colorWithRed:213/255.0 green:218/255.0 blue:218/255.0 alpha:1];
         
         lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _batteryView.width, _batteryView.height)];
         
         //lbl.text = @"外壳电量";
         lbl.font = [UIFont systemFontOfSize:13];
         [_batteryView addSubview:lbl];
         lbl.textColor = [UIColor blackColor];
         */
        NSArray *ibs = [[NSBundle mainBundle ] loadNibNamed:@"BatteryView" owner:self options:nil];
        
        _batteryView = [ibs objectAtIndex:0];
        _batteryView.frame =CGRectMake(0, SCREEN_HEIGHT - Battery_H, _batteryView.width,  _batteryView.height);
        
        
        [self.window addSubview:_batteryView];
        
        
        
    }
    
    //[_batteryView nonePower];
    //[_batteryView changeBattery3];
    
    
    [self.window bringSubviewToFront:self.batteryView];
    
    
    [self updateLabels1];
    //  [self userImg];
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateLabels1) userInfo:nil repeats:YES];
}
-(void)hideTabbar{
    [self.tabBarController hideTabbar];
}
-(void)showTabbar{
    [self.tabBarController showTabbar];
    
}

-(void)setSelected:(int)index
{
    [self.tabBarController setSelected:index];
}
-(void)tabbarSelect:(int) index

{
    [self.tabBarController tabbarSelect:index];

}
#pragma mark captuvo method

-(void)captuvoConnected{
alert = [[UIAlertView alloc]initWithTitle:nil
                                               message:@"----------扫描机器连接"
                                              delegate:nil 
                                     cancelButtonTitle:nil
                                     otherButtonTitles:nil];
[alert show];
    [[Captuvo sharedCaptuvoDeviceDebug] addCaptuvoDelegate:self];
    [[Captuvo sharedCaptuvoDevice] startDecoderHardware] ;
    [[Captuvo sharedCaptuvoDevice]enableCaptuvoDebug:YES];
   [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector: @selector(performDismiss:)  userInfo:nil repeats:NO];
   // [alert performSelector:@selector(endAlertViewDismiss) withObject:nil afterDelay:1.0];
}


-(void) performDismiss:(NSTimer *)timer
{
    [alert dismissWithClickedButtonIndex:0 animated:NO];
    //[alert release];
}

-(void)captuvoDisconnected{
   alert = [[UIAlertView alloc]initWithTitle:nil
                                               message:@"扫描机器失去连接，请重新连接!"
                                              delegate:nil 
                                     cancelButtonTitle:@"知道"
                                     otherButtonTitles:nil];
       // aUIAlertView=alert;
   [alert show];
   // timer=[NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector: @selector(performDismiss:)  userInfo:nil repeats:NO];
    //[alert performSelector:@selector(endAlertViewDismiss) withObject:nil afterDelay:1.0];
}

- (void)redirectNSLogToDocumentFolder{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName =[NSString stringWithFormat:@"%@.log",[NSDate date]];
NSString *logFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
}



-(void)updateLabels1{
    
    
    //ChargeStatus chargeStatus = [[Captuvo sharedCaptuvoDevice]getChargeStatus];
    BatteryStatus BatteryStatus = [[Captuvo sharedCaptuvoDevice]getBatteryStatus];

    switch (BatteryStatus) {
        case BatteryStatusPowerSourceConnected:
            //lbl.text = @"外壳电量:|*AC*|";
            //lbl.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"battery-charging"]];
            [_batteryView charging];
            break;
        case BatteryStatus4Of4Bars:
            //lbl.text = @"外壳电量:|****|";
            //lbl.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"battery-process"]];
            [_batteryView changeBattery];
            break;
        case BatteryStatus3Of4Bars:
            //lbl.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"battery-process"]];
            [_batteryView changeBattery3];
            break;
        case BatteryStatus2Of4Bars:
            //lbl.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"battery-process_low"]];
            [_batteryView changeBattery2];
            break;
        case BatteryStatus1Of4Bars:
            //lbl.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"battery-process_low"]];
            [_batteryView  lowPower];
            break;
        case BatteryStatus0Of4Bars:
            lbl.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"battery-none"]];
            [_batteryView nonePower];
            break;
        case BatteryStatusUndefined:
            //lbl.text = @"外壳电量:未连接";
            //lbl.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"battery-none"]];
            
            [_batteryView Undefined];
        default:
            break;
    }
    
//    UIAlertView *alertv= [[UIAlertView alloc] initWithTitle:@"test" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
//    [alertv  show];
    
//    
//    if (self.updating) {
//        
//        double delayInSeconds = 2.0;
//        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
//        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//            [self updateLabels];
//        });
//    }
    
}



@end
